package org.wzy.springcloud.feign.web.controller;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.wzy.springcloud.feign.api.domain.Person;
import org.wzy.springcloud.feign.api.service.PersonService;

import java.util.ArrayList;
import java.util.Collection;

/**
 * {@link PersonClientController} 可选实现 {@link PersonService}(上方代码是不实现，下方实现)
 *
 * @author wzy
 * @version 1.0
 * @date 2017/11/20 23:21
 */
@RestController
public class PersonClientController {
    private PersonService personService;

    @Autowired
    public PersonClientController(PersonService personService) {
        this.personService = personService;
    }

    // 这里的url可以不和FeignClient API定义的url一致
    @PostMapping("/person/save")
    public String save(@RequestBody Person person) {
        String result = "";
        try {
            result = personService.save(person);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return result;
    }

    // 这里的url可以不和FeignClient API定义的url一致
    @GetMapping("/person/find/all")
    @HystrixCommand(
            commandKey = "personFindAll",
            commandProperties = {
                    @HystrixProperty(name = "execution.isolation.strategy", value = "THREAD"),
                    @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "100")
            },
            fallbackMethod = "personFindAllFallback",
            threadPoolKey = "person-operates",
            threadPoolProperties = {
                    @HystrixProperty(name = "coreSize", value = "10"),
                    @HystrixProperty(name = "maximumSize", value = "10"),
                    @HystrixProperty(name = "maxQueueSize", value = "100"),
                    @HystrixProperty(name = "allowMaximumSizeToDivergeFromCoreSize", value = "true"),
                    @HystrixProperty(name = "keepAliveTimeMinutes", value = "0"),
            })
    public Collection<Person> personFindAll() {
        Collection<Person> all = null;
        try {
            all = personService.findAll();
        } catch (Exception e) {
            System.out.println("下层应用抛出的异常被成功捕获到~~~~~~~~~~~~~~~~~~~~~~~~~~~");
        }

        return all;
    }

    public Collection<Person> personFindAllFallback() {
        System.out.println("进入 personFindAll 熔断方法，说明服务器接口请求超时了...");
        return new ArrayList<>();
    }
}
